package com.example.pool.httpTest.util;

// 用到的等待处理回调的类
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.util.EntityUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class CallbackTask implements FutureCallback<HttpResponse> {
    private CountDownLatch latch;

    // 区分http请求
    private String name;

    private long startTime;

    public CallbackTask(CountDownLatch latch, String name, long startTime) {
        this.latch = latch;
        this.name = name;
        this.startTime = startTime;
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");

    @SneakyThrows
    @Override
    public void completed(final HttpResponse response2) {

        latch.countDown();
        String result = EntityUtils.toString(response2.getEntity());
        log.info("收到回复:{},return:{},耗时：{}, 当前系统时间：{}", name + response2.getStatusLine(), result, System.currentTimeMillis() - startTime, simpleDateFormat.format(new Date()));
        /**
         * 这个地方的业务逻辑的处理速度，影响整体的处理速度。原因是只有一个线程工作。
         * 提供个人优化思路：可以将获取到的回调结果放入队列，开启多个消费者进行监听。
         * 一是能避免业务逻辑处理较慢降低单线程效率。二是逻辑解耦，后续扩展起来也便利。
         */
//        long random = (long)(Math.random() * 3 * 1000);
        Thread.sleep(3000);
//        wait(3000);
        System.out.println("thread:"+Thread.currentThread().getName());

    }

    @Override
    public void failed(final Exception ex) {
        latch.countDown();
        System.out.println(name + "发生异常" + ":" + ex.getMessage());
    }

    @Override
    public void cancelled() {
        latch.countDown();
        System.out.println(name + " cancelled");
    }
}
